package com.elm.controller;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.elm.entity.Cart;
import com.elm.service.CartService;
import com.elm.service.impl.CartServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class CartController implements BaseController{
    private final CartService cartService;

    public CartController() {
        cartService = new CartServiceImpl();
    }
    @Override
    public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String action = req.getPathInfo().split("/")[2];
        switch (action) {
            case "listCart":
                getListCartByUserIdAndBusinessId(req, resp);
                break;
            case "saveCart":
                doSaveCart(req, resp);
                break;
            case "updateCart":
                doUpdateCart(req, resp);
                break;
            case "removeCart":
                doRemoveCart(req, resp);
                break;
        }
    }

    /**
     * 查询购物车
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void getListCartByUserIdAndBusinessId(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException, SQLException {

        // 获取必要参数
        String userId = req.getParameter("userId");

        // 获取可选参数businessId
        String businessIdParam = req.getParameter("businessId");
        Integer businessId = null;

        // 解析businessId（如果存在）
        if (businessIdParam != null && !businessIdParam.isEmpty()) {
            businessId = Integer.parseInt(businessIdParam);
        }

        List<Cart> carts;
        resp.setContentType("application/json;charset=UTF-8");
        try {
            // 根据是否提供businessId执行不同的查询
            if (businessId != null) {
                carts = cartService.getCartListByUserIdAndBusinessId(userId, businessId);
            } else {
                carts = cartService.getCartListByUserId(userId); // 新增方法：查询用户所有购物车
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw e;
        }
        resp.getWriter().write(new Gson().toJson(carts));
    }


    /**
     * 添加购物车
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doSaveCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        Cart cart = new Cart();
        cart.setUserId(req.getParameter("userId"));
        cart.setBusinessId(Integer.valueOf(req.getParameter("businessId")));
        cart.setFoodId(Integer.valueOf(req.getParameter("foodId")));

        int result = cartService.saveCart(cart);
        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().write(new Gson().toJson(result));
    }

    /**
     * 修改购物车
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doUpdateCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cart cart = new Cart();
        cart.setUserId(req.getParameter("userId"));
        cart.setBusinessId(Integer.valueOf(req.getParameter("businessId")));
        cart.setFoodId(Integer.valueOf(req.getParameter("foodId")));
        cart.setQuantity(Integer.valueOf(req.getParameter("quantity")));

        int result = cartService.updateCart(cart);

        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().write(new Gson().toJson(result));
    }

    /**
     * 删除购物车
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doRemoveCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        Cart cart = new Cart();
        cart.setUserId(req.getParameter("userId"));
        cart.setBusinessId(Integer.valueOf(req.getParameter("businessId")));
        cart.setFoodId(Integer.valueOf(req.getParameter("foodId")));

        int result = cartService.removeCart(cart);

        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().write(new Gson().toJson(result));
    }
}
